package com.sinoglobal.dumping.util;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 创建贺卡图片
 * Created by Administrator on 2016/1/12.
 */
public class Dumpling_FileUtils {
    public static String imageFileName;

    public static File createTempFile(Context context, String userId) {
        String state = Environment.getExternalStorageState();
        String currentTime = System.currentTimeMillis() + "";
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File pic = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File tempFile = new File(pic, currentTime + "_" + userId + ".jpg");
            imageFileName = createFileName(currentTime, userId)+".jpg";
            return tempFile;
        } else {
            File cacheFile = context.getCacheDir();
            File tempFile = new File(cacheFile, currentTime + "_" + userId + ".jpg");
            imageFileName = createFileName(currentTime, userId)+".jpg";
            return tempFile;
        }
    }

    private static String createFileName(String currentTime, String userId) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("Congratulation/");
        stringBuilder.append(submit(currentTime) + "/");
        stringBuilder.append(submit(userId) + "/");
        stringBuilder.append(currentTime + "_" + userId);
        return stringBuilder.toString();
    }

    private static String submit(String string) {
        string = Dumpling_Md5Util.string2Md5(string);
        return string.substring(24, 28);
    }
    
    public static void copyAssets2SD(Context context, String fileName, String outPath) throws IOException {
        InputStream myInput;
        OutputStream myOutput = new FileOutputStream(outPath);
        myInput = context.getAssets().open(fileName);
        Log.e("copyAssets2SD",fileName+"=="+outPath);
        byte[] buffer = new byte[1024];
        int length = myInput.read(buffer);
        while(length > 0)
        {
            myOutput.write(buffer, 0, length);
            length = myInput.read(buffer);
        }

        myOutput.flush();
        myInput.close();
        myOutput.close();
    }
}
